package com.lzb.compressmaster.utils;

import android.media.MediaMetadataRetriever;
import android.text.TextUtils;
import android.util.Log;

import com.arthenica.ffmpegkit.FFmpegKit;
import com.arthenica.ffmpegkit.FFmpegSession;
import com.arthenica.ffmpegkit.ReturnCode;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lzb.compressmaster.Content;

import org.json.JSONObject;
import org.json.JSONArray;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 视频压缩工具类
 * 支持四种压缩模式：智能压缩、清晰优先、缩小优先、自定义
 *
 * @author lzb
 */
public class VideoCompressor {

    private static final String TAG = "VideoCompressor";

    /**
     * 压缩类型枚举
     */
    public enum CompressType {
        SMART("智能压缩"),          // 智能压缩
        QUALITY_FIRST("清晰优先"),  // 清晰优先
        SIZE_FIRST("缩小优先"),     // 缩小优先
        CUSTOM("自定义");          // 自定义

        private final String name;

        CompressType(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return name;
        }
    }

    /**
     * 压缩配置类
     */
    public static class CompressConfig {
        private CompressType type = CompressType.SMART;
        private int width = 0;          // 自定义宽度，0表示保持原始
        private int height = 0;         // 自定义高度，0表示保持原始
        private int frameRate = 0;      // 自定义帧率，0表示保持原始
        private int crf = 23;           // 质量因子 (18-28，越小质量越好)
        private int bitrate = 0;        // 自定义比特率(bps)，0表示自动
        private boolean keepAspectRatio = false;  // 是否保持宽高比
        private String preset = "medium"; // 编码预设

        // 构造函数
        public CompressConfig() {
        }

        public CompressConfig(CompressType type) {
            this.type = type;
        }

        // Getter和Setter方法
        public CompressType getCompressType() {
            return type;
        }

        public void setCompressType(CompressType type) {
            this.type = type;
        }

        public int getWidth() {
            return width;
        }

        public void setWidth(int width) {
            this.width = width;
        }

        public int getHeight() {
            return height;
        }

        public void setHeight(int height) {
            this.height = height;
        }

        public int getFrameRate() {
            return frameRate;
        }

        public void setFrameRate(int frameRate) {
            this.frameRate = frameRate;
        }

        public int getCrf() {
            return crf;
        }

        public void setCrf(int crf) {
            this.crf = Math.max(18, Math.min(28, crf));
        }

        public int getBitrate() {
            return bitrate;
        }

        public void setBitrate(int bitrate) {
            this.bitrate = bitrate;
        }

        public boolean isKeepAspectRatio() {
            return keepAspectRatio;
        }

        public void setKeepAspectRatio(boolean keepAspectRatio) {
            this.keepAspectRatio = keepAspectRatio;
        }

        public String getPreset() {
            return preset;
        }

        public void setPreset(String preset) {
            this.preset = preset;
        }
    }

    /**
     * 获取视频信息
     */
    public static class VideoInfo {
        private String path;
        private int width;
        private int height;
        private int frameRate;
        private long duration;      // 毫秒
        private long fileSize;      // 字节
        private String codec;
        private String format;

        // Getter和Setter方法
        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        public int getWidth() {
            return width;
        }

        public void setWidth(int width) {
            this.width = width;
        }

        public int getHeight() {
            return height;
        }

        public void setHeight(int height) {
            this.height = height;
        }

        public int getFrameRate() {
            return frameRate;
        }

        public void setFrameRate(int frameRate) {
            this.frameRate = frameRate;
        }

        public long getDuration() {
            return duration;
        }

        public void setDuration(long duration) {
            this.duration = duration;
        }

        public long getFileSize() {
            return fileSize;
        }

        public void setFileSize(long fileSize) {
            this.fileSize = fileSize;
        }

        public String getCodec() {
            return codec;
        }

        public void setCodec(String codec) {
            this.codec = codec;
        }

        public String getFormat() {
            return format;
        }

        public void setFormat(String format) {
            this.format = format;
        }

        @Override
        public String toString() {
            return "VideoInfo{" +
                    "path='" + path + '\'' +
                    ", width=" + width +
                    ", height=" + height +
                    ", frameRate=" + frameRate +
                    ", duration=" + duration +
                    ", fileSize=" + fileSize +
                    ", codec='" + codec + '\'' +
                    ", format='" + format + '\'' +
                    '}';
        }
    }

    /**
     * 构建FFmpeg命令
     */
    public static String buildFfmpegCommand(String inputPath, String outputPath, CompressConfig config) {
        StringBuilder command = new StringBuilder();

        // 输入文件
        command.append("-i \"").append(inputPath).append("\"");

        // 根据压缩类型构建命令
        switch (config.getCompressType()) {
            case SMART:
                command.append(buildSmartCompressCommand(inputPath, config));
                break;
            case QUALITY_FIRST:
                command.append(buildQualityFirstCommand(inputPath, config));
                break;
            case SIZE_FIRST:
                command.append(buildSizeFirstCommand(inputPath, config));
                break;
            case CUSTOM:
                command.append(buildCustomCommand(config));
                break;
        }

        // 输出文件
        command.append(" \"").append(outputPath).append("\"");

        return command.toString();
    }

    /**
     * 智能压缩
     * 根据视频大小和时长自动选择最佳参数
     */
    private static String buildSmartCompressCommand(String inputPath, CompressConfig config) {
        VideoInfo info = getVideoInfo(inputPath);
        if (info == null) {
            return " -c:v libx264 -crf 23 -preset medium";
        }

        long fileSizeMB = info.getFileSize() / (1024 * 1024);
        int originalWidth = info.getWidth();
        int originalHeight = info.getHeight();

        // 根据文件大小决定压缩策略
        StringBuilder command = new StringBuilder();

        if (fileSizeMB > 100) {
            // 大文件：较大压缩
            int targetWidth = Math.min(originalWidth, 1280);
            int targetHeight = calculateHeight(originalWidth, originalHeight, targetWidth);
            command.append(" -vf scale=").append(targetWidth).append(":").append(targetHeight);
            command.append(" -crf 25");
        } else if (fileSizeMB > 50) {
            // 中等文件：适中压缩
            int targetWidth = Math.min(originalWidth, 1920);
            int targetHeight = calculateHeight(originalWidth, originalHeight, targetWidth);
            command.append(" -vf scale=").append(targetWidth).append(":").append(targetHeight);
            command.append(" -crf 23");
        } else {
            // 小文件：轻微压缩
            command.append(" -crf 28");
        }

        command.append(" -preset medium -c:v libx264 -c:a aac -b:a 128k");
        return command.toString();
    }

    /**
     * 清晰优先
     * 保持较高质量，适当降低分辨率
     */
    private static String buildQualityFirstCommand(String inputPath, CompressConfig config) {
        VideoInfo info = getVideoInfo(inputPath);
        if (info == null) {
            return " -c:v libx264 -crf 18 -preset slow";
        }

        int originalWidth = info.getWidth();
        int originalHeight = info.getHeight();

        StringBuilder command = new StringBuilder();

        // 轻微降低分辨率
        int targetWidth = Math.min(originalWidth, 1920);
        int targetHeight = calculateHeight(originalWidth, originalHeight, targetWidth);

        if (targetWidth < originalWidth) {
            command.append(" -vf scale=").append(targetWidth).append(":").append(targetHeight);
        }

        command.append(" -crf 18 -preset slow -c:v libx264 -c:a aac -b:a 192k");
        return command.toString();
    }

    /**
     * 缩小优先
     * 大幅降低文件大小，接受一定质量损失
     */
    private static String buildSizeFirstCommand(String inputPath, CompressConfig config) {
        VideoInfo info = getVideoInfo(inputPath);
        if (info == null) {
            return " -c:v libx264 -crf 28 -preset fast -vf scale=1280:-2";
        }

        int originalWidth = info.getWidth();
        int originalHeight = info.getHeight();

        StringBuilder command = new StringBuilder();

        // 显著降低分辨率
        int targetWidth = Math.min(originalWidth, 854); // 480p
        int targetHeight = calculateHeight(originalWidth, originalHeight, targetWidth);

        command.append(" -vf scale=").append(targetWidth).append(":").append(targetHeight);
        command.append(" -crf 28 -preset fast -c:v libx264 -c:a aac -b:a 96k");

        return command.toString();
    }

    /**
     * 自定义压缩
     * 用户可以自定义分辨率、帧率和质量
     */
    private static String buildCustomCommand(CompressConfig config) {
        StringBuilder command = new StringBuilder();

        // 视频滤镜
        StringBuilder filter = new StringBuilder();

        // 分辨率设置
        if (config.getWidth() > 0 || config.getHeight() > 0) {
            int width = config.getWidth();
            int height = config.getHeight();

            if (config.isKeepAspectRatio() && width > 0 && height == 0) {
                filter.append("scale=").append(width).append(":-2");
            } else if (config.isKeepAspectRatio() && height > 0 && width == 0) {
                filter.append("scale=-2:").append(height);
            } else if (width > 0 && height > 0) {
                filter.append("scale=").append(width).append(":").append(height);
            }
        }

        // 帧率设置
        if (config.getFrameRate() > 0) {
            if (filter.length() > 0) filter.append(",");
            filter.append("fps=").append(config.getFrameRate());
        }

        if (filter.length() > 0) {
            command.append(" -vf \"").append(filter).append("\"");
        }

        // 质量设置
//        if (config.getBitrate() > 0) {
//            command.append(" -b:v ").append(config.getBitrate());
//        } else {
//            command.append(" -crf ").append(config.getCrf());
//        }

        command.append(" -preset ").append(config.getPreset());
        command.append(" -c:v libx264 -c:a aac -b:a 128k");

        return command.toString();
    }

    /**
     * 计算等比例高度
     */
    private static int calculateHeight(int originalWidth, int originalHeight, int targetWidth) {
        if (originalWidth <= 0) return originalHeight;
        return Math.round((float) originalHeight * targetWidth / originalWidth);
    }

    /**
     * 获取视频信息
     * 使用FFmpeg命令行工具获取真实视频信息
     */
    public static VideoInfo getVideoInfo(String videoPath) {
        if (!new File(videoPath).exists()) {
            Log.e(TAG, "视频文件不存在: " + videoPath);
            return null;
        }

        VideoInfo info = new VideoInfo();
        info.setPath(videoPath);
        info.setFileSize(new File(videoPath).length());

        try {
            // 使用FFprobe命令获取视频信息
            String[] cmd = {
                    "ffprobe",
                    "-v", "quiet",
                    "-print_format", "json",
                    "-show_format",
                    "-show_streams",
                    videoPath
            };

            // 执行命令并获取输出
            Process process = Runtime.getRuntime().exec(cmd);
            java.io.BufferedReader reader = new java.io.BufferedReader(
                    new java.io.InputStreamReader(process.getInputStream())
            );

            StringBuilder output = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line);
            }

            int exitCode = process.waitFor();
            if (exitCode != 0) {
                Log.e(TAG, "FFprobe执行失败，退出码: " + exitCode);
                return getVideoInfoFallback(videoPath);
            }

            // 解析JSON输出
            String jsonOutput = output.toString();
            return parseVideoInfoFromJson(jsonOutput, info);

        } catch (Exception e) {
            Log.e(TAG, "使用FFmpeg获取视频信息失败: " + e.getMessage(), e);

            // 降级使用MediaMetadataRetriever
            return getVideoInfoFallback(videoPath);
        }
    }

    /**
     * 从FFprobe JSON输出解析视频信息
     */
    private static VideoInfo parseVideoInfoFromJson(String jsonOutput, VideoInfo info) {
        try {
            org.json.JSONObject json = new org.json.JSONObject(jsonOutput);

            // 解析format信息
            if (json.has("format")) {
                org.json.JSONObject format = json.getJSONObject("format");
                if (format.has("duration")) {
                    info.setDuration((long) (format.getDouble("duration") * 1000));
                }
                if (format.has("format_name")) {
                    info.setFormat(format.getString("format_name"));
                }
            }

            // 解析streams信息
            if (json.has("streams")) {
                org.json.JSONArray streams = json.getJSONArray("streams");
                for (int i = 0; i < streams.length(); i++) {
                    org.json.JSONObject stream = streams.getJSONObject(i);

                    // 只处理视频流
                    if ("video".equals(stream.optString("codec_type"))) {
                        info.setWidth(stream.getInt("width"));
                        info.setHeight(stream.getInt("height"));
                        info.setCodec(stream.getString("codec_name"));

                        // 获取帧率
                        String frameRateStr = stream.optString("r_frame_rate", "30/1");
                        if (frameRateStr.contains("/")) {
                            String[] parts = frameRateStr.split("/");
                            int numerator = Integer.parseInt(parts[0]);
                            int denominator = Integer.parseInt(parts[1]);
                            if (denominator != 0) {
                                info.setFrameRate(numerator / denominator);
                            } else {
                                info.setFrameRate(30);
                            }
                        } else {
                            info.setFrameRate(Integer.parseInt(frameRateStr));
                        }
                        break;
                    }
                }
            }

            Log.d(TAG, "FFmpeg视频信息获取成功: " + info.toString());
            return info;

        } catch (Exception e) {
            Log.e(TAG, "解析FFprobe输出失败: " + e.getMessage(), e);
            return getVideoInfoFallback(info.getPath());
        }
    }

    /**
     * 降级使用MediaMetadataRetriever获取视频信息
     */
    private static VideoInfo getVideoInfoFallback(String videoPath) {
        if (!new File(videoPath).exists()) {
            Log.e(TAG, "视频文件不存在: " + videoPath);
            return null;
        }

        VideoInfo info = new VideoInfo();
        info.setPath(videoPath);
        info.setFileSize(new File(videoPath).length());

        MediaMetadataRetriever retriever = null;
        try {
            retriever = new MediaMetadataRetriever();
            retriever.setDataSource(videoPath);

            // 获取宽度
            String widthStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
            if (widthStr != null) {
                info.setWidth(Integer.parseInt(widthStr));
            }

            // 获取高度
            String heightStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
            if (heightStr != null) {
                info.setHeight(Integer.parseInt(heightStr));
            }

            // 获取时长（毫秒）
            String durationStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            if (durationStr != null) {
                info.setDuration(Long.parseLong(durationStr));
            }

            // 获取帧率
            String frameRateStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE);
            if (frameRateStr == null) {
                frameRateStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_FRAME_COUNT);
                if (frameRateStr != null && info.getDuration() > 0) {
                    long frameCount = Long.parseLong(frameRateStr);
                    info.setFrameRate((int) (frameCount / (info.getDuration() / 1000.0)));
                } else {
                    info.setFrameRate(30); // 默认值
                }
            } else {
                info.setFrameRate((int) Float.parseFloat(frameRateStr));
            }

            // 获取MIME类型
            String mimeType = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
            if (mimeType != null) {
                info.setFormat(mimeType.split("/")[1]);
            }

            Log.d(TAG, "降级视频信息获取成功: " + info.toString());
            return info;

        } catch (Exception e) {
            Log.e(TAG, "降级获取视频信息失败: " + e.getMessage(), e);
            return null;
        } finally {
            if (retriever != null) {
                try {
                    retriever.release();
                } catch (Exception e) {
                    Log.e(TAG, "释放MediaMetadataRetriever失败", e);
                }
            }
        }
    }

    /**
     * 获取支持的视频格式
     */
    public static boolean isSupportedVideo(String filePath) {
        if (TextUtils.isEmpty(filePath)) return false;

        String extension = filePath.toLowerCase();
        return extension.endsWith(".mp4") ||
                extension.endsWith(".avi") ||
                extension.endsWith(".mov") ||
                extension.endsWith(".mkv") ||
                extension.endsWith(".flv") ||
                extension.endsWith(".wmv") ||
                extension.endsWith(".3gp") ||
                extension.endsWith(".webm");
    }

    /**
     * 获取文件大小（MB）
     */
    public static double getFileSizeMB(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) return 0;
        return file.length() / (1024.0 * 1024.0);
    }

    /**
     * 创建预设配置
     */
    public static CompressConfig createSmartConfig() {
        return new CompressConfig(CompressType.SMART);
    }

    public static CompressConfig createQualityFirstConfig() {
        return new CompressConfig(CompressType.QUALITY_FIRST);
    }

    public static CompressConfig createSizeFirstConfig() {
        return new CompressConfig(CompressType.SIZE_FIRST);
    }

    public static CompressConfig createCustomConfig() {
        return new CompressConfig(CompressType.CUSTOM);
    }

    /**
     * 视频压缩回调接口
     */
    public interface CompressCallback {
        /**
         * 压缩完成
         *
         * @param result 压缩结果对象，包含输出路径、文件大小、压缩状态等信息
         */
        void onComplete(CompressResult result);

        /**
         * 压缩失败
         *
         * @param error 错误信息
         */
        void onError(String error);
    }

    /**
     * 异步压缩视频
     *
     * @param inputPath  输入视频路径
     * @param outputPath 输出视频路径
     * @param config     压缩配置
     * @param callback   压缩回调
     */
    public static void compressVideo(String inputPath, String outputPath, CompressConfig config, CompressCallback callback) {
        if (callback == null) {
            throw new IllegalArgumentException("回调不能为空");
        }

        if (!new File(inputPath).exists()) {
            callback.onError("输入文件不存在: " + inputPath);
            return;
        }

        // 创建输出目录
        File outputFile = new File(outputPath);
        File parentFile = outputFile.getParentFile();
        if (parentFile != null && !parentFile.exists()) {
            parentFile.mkdirs();
        }

        String fileName = FileUtils.getFileNameNoExtension(outputPath);
        String extension = FileUtils.getFileExtension(outputPath);

        int counter = 1;
        while (outputFile.exists()) {
            String outputFileName = fileName + "_" + counter + "." + extension;
            outputFile = new File(parentFile, outputFileName);
            counter++;
        }

        File finalOutputFile = outputFile;
        new Thread(() -> {
            try {
                long startTime = System.currentTimeMillis();

                // 获取原始文件大小
                long originalSize = new File(inputPath).length();

                // 构建FFmpeg命令
                String command = buildFfmpegCommand(inputPath, finalOutputFile.getAbsolutePath(), config);
                Log.d(TAG, "执行压缩命令: " + command);

                // 执行压缩
                boolean success = executeFfmpegCommand(command);

                if (success) {
                    long endTime = System.currentTimeMillis();
                    long duration = endTime - startTime;

                    // 检查输出文件
                    if (finalOutputFile.exists() && finalOutputFile.length() > 0) {
                        long compressedSize = finalOutputFile.length();

                        Log.d(TAG, String.format("压缩完成: 原始大小=%dMB, 压缩后=%dMB, 压缩率=%.2f%%, 耗时=%d秒",
                                originalSize / (1024 * 1024),
                                compressedSize / (1024 * 1024),
                                (1 - (double) compressedSize / originalSize) * 100,
                                duration / 1000));

                        // 创建CompressResult对象
                        CompressResult result = new CompressResult(inputPath, finalOutputFile.getAbsolutePath(), 
                                true, null, originalSize, compressedSize, duration);
                        callback.onComplete(result);
                    } else {
                        CompressResult result = new CompressResult(inputPath, finalOutputFile.getAbsolutePath(), 
                                false, "压缩失败：输出文件为空或不存在", originalSize, 0, 0);
                        callback.onComplete(result);
                    }
                } else {
                    CompressResult result = new CompressResult(inputPath, finalOutputFile.getAbsolutePath(), 
                            false, "FFmpeg执行失败", 0, 0, 0);
                    callback.onComplete(result);
                }

            } catch (Exception e) {
                Log.e(TAG, "压缩过程异常", e);
                CompressResult result = new CompressResult(inputPath, finalOutputFile.getAbsolutePath(), 
                        false, "压缩失败: " + e.getMessage(), 0, 0, 0);
                callback.onComplete(result);
            }
        }).start();
    }

    /**
     * 异步压缩视频并返回CompressResult
     * @param inputPath 输入视频路径
     * @param outputPath 输出视频路径
     * @param config 压缩配置
     * @param callback 压缩结果回调
     */
    public static void compressVideoAsyncWithResult(String inputPath, String outputPath, CompressConfig config, CompressResultCallback callback) {
        if (callback == null) {
            throw new IllegalArgumentException("回调不能为空");
        }
        
        new Thread(() -> {
            CompressResult result = compressVideoSync(inputPath, outputPath, config);
            callback.onResult(result);
        }).start();
    }

    /**
     * 压缩结果回调接口
     */
    public interface CompressResultCallback {
        void onResult(CompressResult result);
    }

    /**
     * 同步压缩视频
     * @param inputPath 输入视频路径
     * @param outputPath 输出视频路径
     * @param config 压缩配置
     * @return 压缩结果对象
     */
    public static CompressResult compressVideoSync(String inputPath, String outputPath, CompressConfig config) {
        long startTime = System.currentTimeMillis();
        
        // 检查输入文件
        File inputFile = new File(inputPath);
        if (!inputFile.exists()) {
            return new CompressResult(inputPath, outputPath, false, "输入文件不存在: " + inputPath, 0, 0, 0);
        }
        
        long originalSize = inputFile.length();
        
        // 创建输出目录
        File outputFile = new File(outputPath);
        File outputDir = outputFile.getParentFile();
        if (outputDir != null && !outputDir.exists()) {
            if (!outputDir.mkdirs()) {
                return new CompressResult(inputPath, outputPath, false, "无法创建输出目录", originalSize, 0, 0);
            }
        }
        
        // 如果文件已存在，添加时间戳
        if (outputFile.exists()) {
            String fileName = outputFile.getName();
            String parentPath = outputFile.getParent();
            
            int dotIndex = fileName.lastIndexOf('.');
            String baseName = dotIndex > 0 ? fileName.substring(0, dotIndex) : fileName;
            String extension = dotIndex > 0 ? fileName.substring(dotIndex) : "";
            
            int counter = 1;
            String newFileName;
            do {
                newFileName = baseName + "_" + counter + extension;
                outputFile = new File(parentPath, newFileName);
                counter++;
            } while (outputFile.exists());
            
            outputPath = outputFile.getAbsolutePath();
            Log.d(TAG, "输出文件已存在，重命名为: " + outputPath);
        }
        
        try {
            // 构建FFmpeg命令
            String command = buildFfmpegCommand(inputPath, outputPath, config);
            Log.d(TAG, "执行压缩命令: " + command);
            
            // 执行压缩
            boolean success = executeFfmpegCommand(command);
            
            if (success) {
                long endTime = System.currentTimeMillis();
                long duration = endTime - startTime;
                
                // 检查输出文件
                if (outputFile.exists() && outputFile.length() > 0) {
                    long compressedSize = outputFile.length();
                    
                    Log.d(TAG, String.format("压缩完成: 原始大小=%dMB, 压缩后=%dMB, 压缩率=%.2f%%, 耗时=%d秒",
                            originalSize / (1024 * 1024),
                            compressedSize / (1024 * 1024),
                            (1 - (double) compressedSize / originalSize) * 100,
                            duration / 1000));
                    
                    return new CompressResult(inputPath, outputPath, true, null, originalSize, compressedSize, duration);
                } else {
                    String error = "压缩失败：输出文件为空或不存在";
                    Log.e(TAG, error);
                    return new CompressResult(inputPath, outputPath, false, error, originalSize, 0, 0);
                }
            } else {
                String error = "FFmpeg执行失败";
                Log.e(TAG, error);
                return new CompressResult(inputPath, outputPath, false, error, originalSize, 0, 0);
            }
            
        } catch (Exception e) {
            String error = "压缩过程异常: " + e.getMessage();
            Log.e(TAG, error, e);
            return new CompressResult(inputPath, outputPath, false, error, originalSize, 0, 0);
        }
    }

    /**
     * 执行FFmpeg命令
     *
     * @param command FFmpeg命令
     * @return 执行结果
     */
    private static boolean executeFfmpegCommand(String command) {
        try {
            FFmpegSession session = FFmpegKit.execute(command);

            if (ReturnCode.isSuccess(session.getReturnCode())) {
                Log.d(TAG, "FFmpeg命令执行成功");
                return true;
            } else {
                Log.e(TAG, "FFmpeg命令执行失败: " + session.getFailStackTrace());
                return false;
            }

        } catch (Exception e) {
            Log.e(TAG, "执行FFmpeg命令异常", e);
            return false;
        }
    }

    /**
     * 压缩结果类
     */
    public static class CompressResult {
        private String inputPath;
        private String outputPath;
        private boolean success;
        private String errorMessage;
        private long originalSize;
        private long compressedSize;
        private long duration;

        public CompressResult(String inputPath, String outputPath, boolean success,
                              String errorMessage, long originalSize, long compressedSize, long duration) {
            this.inputPath = inputPath;
            this.outputPath = outputPath;
            this.success = success;
            this.errorMessage = errorMessage;
            this.originalSize = originalSize;
            this.compressedSize = compressedSize;
            this.duration = duration;
        }

        public String getInputPath() {
            return inputPath;
        }

        public String getOutputPath() {
            return outputPath;
        }

        public void setOutputPath(String outputPath) {
            this.outputPath = outputPath;
        }

        public boolean isSuccess() {
            return success;
        }

        public String getErrorMessage() {
            return errorMessage;
        }

        public long getOriginalSize() {
            return originalSize;
        }

        public long getCompressedSize() {
            return compressedSize;
        }

        public long getDuration() {
            return duration;
        }

        public double getCompressRatio() {
            if (originalSize > 0) {
                return (1.0 - (double) compressedSize / originalSize) * 100;
            }
            return 0.0;
        }

        public String getFormattedOriginalSize() {
            return formatFileSize(originalSize);
        }

        public String getFormattedCompressedSize() {
            return formatFileSize(compressedSize);
        }

        private String formatFileSize(long size) {
            if (size <= 0) return "0 B";

            final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
            int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
            return String.format("%.1f %s",
                    size / Math.pow(1024, digitGroups),
                    units[digitGroups]);
        }

        @Override
        public String toString() {
            return "CompressResult{" +
                    "inputPath='" + inputPath + '\'' +
                    ", outputPath='" + outputPath + '\'' +
                    ", success=" + success +
                    ", errorMessage='" + errorMessage + '\'' +
                    ", originalSize=" + getFormattedOriginalSize() +
                    ", compressedSize=" + getFormattedCompressedSize() +
                    ", compressRatio=" + String.format("%.1f%%", getCompressRatio()) +
                    ", duration=" + duration + "ms" +
                    '}';
        }
    }


}